#include "Power_Task.h"
#include "ADC_DMA.h"
#include "Input.h"
#include "Output.h"

void Power_Task(void* pdata) {
    uint32_t last_time = 0;
    uint32_t cur_time  = 0;
    Power.vol          = Get_battert_vol();   // 上电获取电池电压
    for (;;) {
        cur_time = GetSysTickMs();
        if (cur_time - last_time >= CHECK_BATTERY_TIME) {   // 每隔1h获取电池电压
            Power.vol = Get_battert_vol();
            last_time = cur_time;
        }
        DIN_Proc();
        Power.ac_state = Get_input_state(0);   // 获取电源输入状态
        OSTimeDly(50);
    }
}

// 获取电池电压
uint16_t Get_battert_vol(void) {
    uint16_t vol = 0;
    Output_Control(BATTERY_CHARGE, RELAY_STATE_OFF);              // 断开充电电路
    Power.vol_orign = Read_adc_value(ADC_CHANNEL_PC4);            // 获取原始AD
    vol             = CalculateBatteryVoltage(Power.vol_orign);   // 换算成电压（mv）
    Output_Control(BATTERY_CHARGE, RELAY_STATE_ON);               // 恢复充电电路

    return vol;
}
// 电池电压计算函数
uint32_t CalculateBatteryVoltage(uint16_t adc_value) {
    const uint32_t VREF_MV = 2500;
    const uint32_t R2      = 2000;
    const uint32_t R3      = 470;
    const uint32_t ADC_MAX = 4095;

    uint64_t numerator   = (uint64_t) adc_value * VREF_MV;
    numerator            = numerator * (R2 + R3);
    uint64_t denominator = (uint64_t) ADC_MAX * R3;

    uint64_t battery_voltage_mV = numerator / denominator;

    return (uint32_t) battery_voltage_mV;
}
// 获取电源接入状态
uint16_t Get_Power_ac_state(void) {
    return Power.ac_state;
}
